package c2.advanced.server.configuration;

import easy.java.def.HostType;
import easy.java.practice.errorcode.EcException;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = AdvServerEnv.PROP_PREFIX)
public class AdvServerEnv implements InitializingBean {

    public static final String PROP_PREFIX = "c2";

    public static final String getSecretProp() {
        return PROP_PREFIX+".secret";
    }
    public static final String getConsoleBaseUriProp() {
        return PROP_PREFIX+".console.uri";
    }
    public static final String getApiHostTypeProp() {
        return PROP_PREFIX+".self.apiHostType";
    }
    public static final String getCodeProp() {
        return PROP_PREFIX+".self.code";
    }
    public static final String getExcelPathProp() {
        return PROP_PREFIX+".self.excelPath";
    }

    @Value("${c2.secret}")
    public String secret;
    @Value("${c2.console.uri}")
    public String consoleBaseUri;


    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("AdvServerEnv的配置是{}", this);
    }

    private SelfProperties self;

    /** 是否在调试公共服，无论是演示环境还是外网，这个值都应该是false */
    @Value("${c2.debugShareService:false}")
    private boolean debugShareService;

    @Data
    public static class SelfProperties {
        private String code;
        private boolean debug;
        private String excelPath;
        private String apiHostType = HostType.LAN.code;
    }

    public void checkSecret(String secretValue) {
        if(!StringUtils.equals(secretValue, this.secret)) {
            throw new EcException("秘钥不正确").s();
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("跨服环境配置：");
        if(self == null) {
            sb.append("self节点缺失,");
        } else {
            sb.append(null == self.code ? "self.code缺失, " : "编码：" + self.code+", ");
            sb.append(null == self.excelPath ? "self.excelPath缺失, " : "excel路径：" + self.excelPath+", ");
            sb.append(self.debug ? "debug模式, " : "");
        }
        if(StringUtils.isBlank(consoleBaseUri)) {
            sb.append("consoleBaseUri缺失,");
        } else {
            sb.append("consoleBaseUri=" + consoleBaseUri + ", ");
        }
        return sb.toString();
    }
}
